import React from 'react';
import L from 'leaflet';
import {
  Marker, Popup, Tooltip, withLeaflet
} from 'react-leaflet';
import { isEqual } from 'lodash';
import { isLngLat } from 'src/util/mapUtil';
import setting from './setting';
import defaultImageIcon from '../LMarker/image/flag.png';

class LMarkerIfrema extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      realData: [],
    };
  }

  componentWillReceiveProps(nextProps) {
    const { data } = this.props;
    const { data: nextData } = nextProps;

    if (!isEqual(data, nextData)) {
      this.setState({ realData: nextData });
      if (nextData && nextData[0]) {
        const { lng, lat } = nextData[0];
        this.setDataPool({ lng, lat });
        this.updateEventsDefaultValue({ lng, lat });
      }
    }
  }

  static setting = setting;

  // 获得经纬度点位数组的value边界
  get valueBound() {
    const values = this.resultData.map(item => +item.value || 1);
    return {
      valueMax: Math.max(...values),
      valueMin: Math.min(...values)
    };
  }

  /**
   * 切换显隐不会调用componentWillReceiveProps制造realData数据
   */
  get resultData() {
    const { realData } = this.state;
    let resultData = realData;
    if (Array.isArray(resultData) && resultData.length === 0) {
      const { data } = this.props;
      resultData = data;
    }
    return Array.isArray(resultData) ? resultData : [];
  }

  // 获得点位大小
  getIconSize = (value) => {
    const {
      config: {
        default: { maxSize, minSize }
      }
    } = this.props;

    const { valueMax, valueMin } = this.valueBound;

    if (valueMax === valueMin) return (maxSize + minSize) / 2;

    return Math.floor((maxSize - minSize) * (value - valueMin)
      / (valueMax - valueMin) + minSize);
  };

  // 获得图片icon
  getImageIcon = (value) => {
    const {
      config: {
        default: {
          content: { imageUrl }, position
        }
      }
    } = this.props;

    const size = this.getIconSize(value);
    const iconAnchor = position === 'center'
      ? [size / 2, size / 2] : [size / 2, size];

    return L.icon({
      iconUrl: imageUrl || defaultImageIcon,
      iconSize: [size, size],
      iconAnchor, // 图标中心点
    });
  };

  // 获得散点icon
  getSpotIcon = (value) => {
    const {
      config: {
        default: {
          content: { shape }, position
        }
      }
    } = this.props;
    const size = this.getIconSize(value);
    const color = this.getSpotColor(value);

    return L.divIcon({
      className: 'noBackground',
      html: `<div style="font-size: ${size}px; color: ${color}" class="monetfont icon-${shape}" />`,
      iconSize: [size, size],
      iconAnchor: position === 'center' ? [size / 2, size / 2]
        : [size / 2, size]
    });
  };

  // 获得散点颜色
  getSpotColor = (value) => {
    const { config: { default: { content: { colors } } } } = this.props;
    const set = colors.reduce((pre, item) =>
      (item.start < value && value <= item.end ? item.color : pre), null);
    return set || colors[0].color;
  };

  // 提示框样式
  getTooltipStyle = () => {
    const {
      config: {
        tooltip: {
          font, backgroundColor, borderColor, borderWidth
        }
      }
    } = this.props;

    return {
      border: `${borderWidth}px solid ${borderColor}`,
      backgroundColor,
      ...font
    };
  };

  // 弹窗样式
  getPopupStyle = () => {
    const {
      config: {
        popup: {
          backgroundColor, borderColor, borderWidth,
          width, height
        }
      }
    } = this.props;

    return {
      border: `${borderWidth}px solid ${borderColor}`,
      backgroundColor,
      width,
      height
    };
  };

  // 获得提示框文本
  getTooltipContext = (info) => {
    const infoArray = `${info}`.split(';');
    return (<section
      className="map-marker-content"
      style={this.getTooltipStyle()}
    >
      {infoArray.map((item, idx) =>
        (<React.Fragment key={`line${idx}`}>
          {item}
          <br />
        </React.Fragment>))
      }
    </section>);
  };

  // 获得视频弹出框
  getPopupContext = (url) => (<iframe
    src={url}
    title={url}
    style={this.getPopupStyle()}
  >
  </iframe>)

  // 获得
  getPopupMarker = (lng, lat, url, info, opsValue, index) => {
    const {
      config: {
        action: { show },
        default: { content: { type } },
        popup: { top, right }
      }
    } = this.props;
    const spotIcon = this.getSpotIcon(opsValue);
    const imageIcon = this.getImageIcon(opsValue);

    return (<Marker
      key={`popup${index}${lat}${lng}`}
      position={[lat, lng]}
      icon={type === 'spot' ? spotIcon : imageIcon}
      onClick={(ele) => this.onClickMarker(ele)}
    >
      {<Popup
        position={[lat, lng]}
        className="marker-popup"
        maxWidth={800}
        autoPanPadding={L.point(right, top)}
      >
        {this.getPopupContext(url)}
      </Popup>}

      {info && (show === 'always' || show === 'hover')
      && <Tooltip
        direction="top"
        key={Math.floor(Math.random() * 1000)}
        permanent={show === 'always'}
        className="marker-tooltip"
      >
        {this.getTooltipContext(info)}
      </Tooltip>}
    </Marker>);
  };

  onClickMarker = (ele) => {
    ele && this.setDataPool(ele.latlng);
  };

  // 更新store中的dataPoll
  setDataPool(dataPoll) {
    const {
      bigScreen: { setDataPool },
      events: { click },
      path
    } = this.props;

    setDataPool(click, dataPoll, path);
  }

  // 更新交互事件绑定的默认值
  updateEventsDefaultValue(dataPoll) {
    const {
      bigScreen: { updateEventsDefaultValue }, path, editable
    } = this.props;
    if (!editable) return;
    const eventValues = Object.keys(dataPoll).reduce(
      (pre, key) => Object.assign(pre,
        { [`click.fields.${key}.value`]: dataPoll[key] }), {}
    );
    updateEventsDefaultValue(path, eventValues);
  }

  render() {
    const data = this.resultData;
    if (Array.isArray(data) && data.length > 0) {
      return (
        <React.Fragment>
          { data.filter(({ lng, lat }) => isLngLat(lng, lat))
            .map(({
              lng, lat, value = 1, url, info
            }, index) => this.getPopupMarker(lng, lat, url, info, value, index)) }
        </React.Fragment>
      );
    }
    return null;
  }
}

export default withLeaflet(LMarkerIfrema);
